const Koa = require('koa')
var path = require('path')
const app = new Koa()
const Router = require('koa-router')
let router = new Router()

const mongoose = require('mongoose')
const fs = require('fs')

// 导入所有商品信息
router.get('/insertAllGoodsInfo', async(ctx) => {
  fs.readFile('./data_json/goods.json', 'utf8', (err, data) => {
    // console.log(data)
    data = JSON.parse(data)
    let saveCount = 0
    const Goods = mongoose.model('Goods')
    data.RECORDS.map((value, index) => {
      let newGoods = new Goods(value)
      newGoods.save().then(() => {
        saveCount++
        console.log('成功：' + saveCount)
      }).catch(err => {
        console.log('失败：' + err)
      })
    })
  })
  ctx.body = '开始导入数据'
})

// 导入所有商品分类
router.get('/insertAllCategory', async(ctx) => {
  fs.readFile('./data_json/category.json', 'utf8', (err, data) => {
    data = JSON.parse(data)
    let saveCount = 0
    const Category = mongoose.model('Category')
    data.RECORDS.map((value, index) => {
      // console.log(value)
      let newCategory = new Category(value)
      newCategory.save().then(() => {
        saveCount++
        console.log('成功：' + saveCount)
      }).catch(err => {
        console.log('失败：' + err)
      })
    })
  })
  ctx.body = '开始导入数据'
})

// 导入所有商品二级分类
router.get('/insertAllCategorySub', async(ctx) => {
  fs.readFile('./data_json/category_sub.json', 'utf8', (err, data) => {
    data = JSON.parse(data)
    let saveCount = 0
    const CategorySub = mongoose.model('CategorySub')
    data.RECORDS.map((value, index) => {
      // console.log(value)
      let newCategorySub = new CategorySub(value)
      newCategorySub.save().then(() => {
        saveCount++
        console.log('成功插入：' + saveCount)
      }).catch(err => {
        console.log('插入失败：' + err)
      })
    })
  })
  ctx.body = '开始导入数据'
})

// 获取商品详情接口
router.post('/getDetailGoodsInfo', async(ctx) => {
  let goodsId = ctx.request.body.goodsId
  const Goods = mongoose.model('Goods')
  await Goods.findOne({ ID: goodsId }).exec()
  .then(async(result) => {
    console.log(result)
    ctx.body = { code: 200, message: result }
  })
  .catch(err => {
    console.log(err)
    ctx.body = { code: 500, message: err }
  })
})

// 获取商品一级分类
router.get('/getCategoryList', async(ctx) => {
  try {
    const Category = mongoose.model('Category')
    let result = await Category.find().exec()
    ctx.body = {code: 200, message: result}
  } catch (err) {
    ctx.body = {code: 500, message: err}
  }
})

// 获取商品二级分类
router.get('/getCategorySubList', async(ctx) => {
  try {
    let categoryId = 1
    const CategorySub = mongoose.model('CategorySub')
    let result = await CategorySub.find({MALL_CATEGORY_ID: categoryId}).exec()
    ctx.body = {code: 200, message: result}
  } catch (err) {
    ctx.body = {code: 500, message: err}
  }
})

module.exports = router